package com.kecheng.util;

import java.io.*;  
import java.text.SimpleDateFormat;
import java.util.Date;  
import java.awt.*;  
import java.awt.image.*;  

import javax.imageio.ImageIO;  

import com.kecheng.action.BaseAction;

import com.sun.image.codec.jpeg.*;
/** 
 * 图片压缩处理 
 * @author csyaonie
 */  
public class ImgCompress {  
    private static Image img;  
    //public static String root="C:/Program Files/Apache Software Foundation/Tomcat 7.0/webapps/taoci/upload/";
    private static int w = 400;  //设置图片压缩后的宽度，高度等比例
    public static String compress(File file,String fileFileName,Integer width) throws IOException{
    	BufferedImage buffImg = ImageIO.read(file);
    	
    	//BufferedImage buffImg = ImageIO.read(cmykJPEGFile);
    	
        int ImgWidth = buffImg.getWidth();// 获取原图的宽度
        int ImgHeight = buffImg.getHeight();// 获取原图的高度
        if(width==null || width<w){
        	width=w;
        }
        int height = (width*ImgHeight)/ImgWidth;
        
    	img = ImageIO.read(file);  
    	BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB );   
        image.getGraphics().drawImage(img, 0, 0, width,height, null); // 绘制缩小后的图  
        File destFile = new File(new BaseAction().root,fileFileName);  
        FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流  
        // 可以正常实现bmp、png、gif转jpg  
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
        encoder.encode(image); // JPEG编码  
        out.close();  
        
    	return "upload/"+fileFileName;
    }

}  